# -*- coding: utf-8 -*-

# 轨道例子

import sys, pygame, random, math
from pygame.locals import *
import time as t
from datetime import datetime, date, time

reload(sys)
sys.setdefaultencoding('utf-8')


class Point(object):
    def __init__(self, x, y):
        self.__x = x
        self.__y = y

    def getx(self):
        return self.__x

    def setx(self, x):
        self.__x = x

    x = property(getx, setx)

    def gety(self):
        return self.__y

    def sety(self, y):
        self.__y = y

    y = property(gety, sety)

    def __str__(self):
        return "{X:"+"{:.0f}".format(self.__x)+\
            ",Y:"+"{:.0f}".format(self.__y)+"}"


def print_text(font, x, y, text, color=(255,255,255), shadow=False):
    if shadow:
        imgText = font.render(text, True, (0, 0, 0))
        screen.blit(imgText, (x - 2, y - 2))
    image = font.render(text, True, color)
    screen.blit(image, (x, y))


def wrap_angle(angle):
    return abs(angle %360)

pygame.init()
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("轨道例子")
font1 = pygame.font.Font("freesansbold.ttf", 10)

space = pygame.image.load('space.png').convert()
planet = pygame.image.load('planet2.png').convert_alpha()
ship = pygame.image.load('freelance.png').convert_alpha()
width, height = ship.get_size()
ship = pygame.transform.smoothscale(ship, (width//2, height//2))

pos = Point(0, 0)
old_pos = Point(0, 0)
angle = 0.0
radius = 250

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            sys.exit()

    keys = pygame.key.get_pressed()
    if keys[K_ESCAPE]:
        sys.exit()

    screen.fill((0, 0, 100))

    # 背景
    screen.blit(space, (0, 0))

    # 行星
    width, height = planet.get_size()
    screen.blit(planet, (400-width/2, 300-height/2))

    # 移动飞船
    angle = wrap_angle(angle - 0.5)
    pos.x = math.cos(math.radians(angle)) * radius
    pos.y = math.sin(math.radians(angle)) * radius

    # 旋转
    delta_x = (pos.x - old_pos.x)
    delta_y = (pos.y - old_pos.y)
    rangle = math.atan2(delta_y, delta_x)
    rangled = wrap_angle(-math.degrees(rangle))
    scratch_ship = pygame.transform.rotate(ship, rangled)

    width, height = scratch_ship.get_size()
    screen.blit(scratch_ship, (400 + pos.x - width // 2, 300 + pos.y - height // 2))

    old_pos.x = pos.x
    old_pos.y = pos.y

    print_text(font1, 0, 0, 'Angle: '+'{:.0f}'.format(angle))
    print_text(font1, 0, 20, 'Rotation: '+'{:.2f}'.format(rangle)+'  {:.2f}'.format(rangled))
    print_text(font1, 0, 40, 'Pos: '+str(pos))
    print_text(font1, 0, 60, 'Old Pos: '+str(old_pos))

    pygame.display.update()

    t.sleep(0.016)

